<html lang="en-US">

<head>
    
<title>提高 Go 程序健壮性，Fuzzing 要来了！ - 花落雨忧</title>

<meta property="og:title" content="提高 Go 程序健壮性，Fuzzing 要来了！ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
就在前几天，Go1.17 beta1 正式发布：
兴冲冲本想着看一下当初在 Go1.17 的计划中，预计会支持的新特性：模糊测试（Fuzzing）。不过没想到&amp;hellip;计划赶不上变化，官方正式宣告 Fuzzing 不会出现在 Go1.17 的新功能中。
煎鱼在悲伤之际，发现 Go 在 dev.fuzz 分支上提供了该功能的 Beta 测试，因此今天带大家一起来深入该特性。 &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
就在前几天，Go1.17 beta1 正式发布：
兴冲冲本想着看一下当初在 Go1.17 的计划中，预计会支持的新特性：模糊测试（Fuzzing）。不过没想到&amp;hellip;计划赶不上变化，官方正式宣告 Fuzzing 不会出现在 Go1.17 的新功能中。
煎鱼在悲伤之际，发现 Go 在 dev.fuzz 分支上提供了该功能的 Beta 测试，因此今天带大家一起来深入该特性。 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/fuzzing/">提高 Go 程序健壮性，Fuzzing 要来了！</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/12/31</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>就在前几天，Go1.17 beta1 正式发布：</p>
<p><img src="https://files.mdnice.com/user/3610/fb4ceb3d-ef1c-4c32-a7c3-a4188a0d74b0.png" alt=""></p>
<p>兴冲冲本想着看一下当初在 Go1.17 的计划中，预计会支持的新特性：模糊测试（Fuzzing）。不过没想到&hellip;计划赶不上变化，官方正式宣告 Fuzzing 不会出现在 Go1.17 的新功能中。</p>
<p>煎鱼在悲伤之际，发现 Go 在 dev.fuzz 分支上提供了该功能的 Beta 测试，因此今天带大家一起来深入该特性。</p>
<h2 id="什么是-fuzzing">什么是 Fuzzing</h2>
<p>Fuzzing 是一种自动测试技术，包括向计算机程序提供随机数据作为输入。然后监测程序是否出现恐慌、断言失败、无限循环等。</p>
<p>Fuzzing 不是使用一个小的、预先定义好的手动创建的输入集（如单元测试），而是用新的案例不断地测试代码，以努力 ”锻炼“ 有关软件的所有方面。</p>
<p>这听起来很 ”难“。但在过去的几年里，Fuzzing 的技术水平有了很大的提高。Fuzzing 不再是需要专业知识才能成功使用的东西，现代模糊测试策略能更快、更有效地找到有用的输入。</p>
<p>在应用程序中，就是你只要引入一个 package，对着 API 一顿用就可以了。</p>
<h2 id="为什么要做-fuzzing">为什么要做 Fuzzing</h2>
<p>可能会有小伙伴说，测试？直接人工测试，再把测试数据准备一下，配套 YAPI 等接口管理平台，把自动化接口测试一弄就好了。还需要 Fuzzing 吗？</p>
<p>其实 Fuzzing 是对其他形式的测试、代码审查和静态分析的补充，它通过生成一个随机测试用例去覆盖人为测不到的各种复杂场景。而这些输入几乎不可能人为去构造，总会被传统测试所遗漏。</p>
<h2 id="发生在身边的-fuzzing">发生在身边的 Fuzzing</h2>
<p>实际上 Go-fuzz 对 Go 标准库进行过测试，依然这这之中发现了 200  多个 bug：</p>
<p><img src="https://files.mdnice.com/user/3610/9b00972c-2231-4406-84b8-2e8e44f57d6d.png" alt=""></p>
<p>这还是建立在标准库已经比较成熟，且由非常有经验的开发者编写，在生产中使用多年的情况下，依然有如此多的问题。</p>
<h2 id="快速上手">快速上手</h2>
<p>我们需要在本地执行如下命令，需开启 GO111MODULE 和天梯：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#960050;background-color:#1e0010">$</span> <span style="color:#66d9ef">go</span> <span style="color:#a6e22e">get</span> <span style="color:#a6e22e">golang</span>.<span style="color:#a6e22e">org</span><span style="color:#f92672">/</span><span style="color:#a6e22e">dl</span><span style="color:#f92672">/</span><span style="color:#a6e22e">gotip</span>
</span></span><span style="display:flex;"><span><span style="color:#960050;background-color:#1e0010">$</span> <span style="color:#a6e22e">gotip</span> <span style="color:#a6e22e">download</span> <span style="color:#a6e22e">dev</span>.<span style="color:#a6e22e">fuzz</span>
</span></span></code></pre></div><p>执行完毕后会从 dev.fuzz 分支构建 Go 工具链，同时 gotip 可以作为 go 命令的替代者命令，也就是可以运行 Fuzzing 的相关代码了。</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#75715e">// +build gofuzzbeta
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">tests</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;net/url&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;reflect&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;testing&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">FuzzParseQuery</span>(<span style="color:#a6e22e">f</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">testing</span>.<span style="color:#a6e22e">F</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">f</span>.<span style="color:#a6e22e">Add</span>(<span style="color:#e6db74">&#34;x=1&amp;y=2&#34;</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">f</span>.<span style="color:#a6e22e">Fuzz</span>(<span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">t</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">testing</span>.<span style="color:#a6e22e">T</span>, <span style="color:#a6e22e">queryStr</span> <span style="color:#66d9ef">string</span>) {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">query</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">url</span>.<span style="color:#a6e22e">ParseQuery</span>(<span style="color:#a6e22e">queryStr</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Skip</span>()
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">queryStr2</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">query</span>.<span style="color:#a6e22e">Encode</span>()
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">query2</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">url</span>.<span style="color:#a6e22e">ParseQuery</span>(<span style="color:#a6e22e">queryStr2</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;ParseQuery failed to decode a valid encoded query %s: %v&#34;</span>, <span style="color:#a6e22e">queryStr2</span>, <span style="color:#a6e22e">err</span>)
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">DeepEqual</span>(<span style="color:#a6e22e">query</span>, <span style="color:#a6e22e">query2</span>) {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;ParseQuery gave different query after being encoded\nbefore: %v\nafter: %v&#34;</span>, <span style="color:#a6e22e">query</span>, <span style="color:#a6e22e">query2</span>)
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>	})
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>在相应的目录下执行 <code>gotip test -fuzz=FuzzParseQuery</code> 命令，输出结果：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#a6e22e">fuzzing</span>, <span style="color:#a6e22e">elapsed</span>: <span style="color:#ae81ff">3.0</span><span style="color:#a6e22e">s</span>, <span style="color:#a6e22e">execs</span>: <span style="color:#ae81ff">319</span> (<span style="color:#ae81ff">106</span><span style="color:#f92672">/</span><span style="color:#a6e22e">sec</span>), <span style="color:#a6e22e">workers</span>: <span style="color:#ae81ff">4</span>, <span style="color:#a6e22e">interesting</span>: <span style="color:#ae81ff">15</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">fuzzing</span>, <span style="color:#a6e22e">elapsed</span>: <span style="color:#ae81ff">6.0</span><span style="color:#a6e22e">s</span>, <span style="color:#a6e22e">execs</span>: <span style="color:#ae81ff">665</span> (<span style="color:#ae81ff">111</span><span style="color:#f92672">/</span><span style="color:#a6e22e">sec</span>), <span style="color:#a6e22e">workers</span>: <span style="color:#ae81ff">4</span>, <span style="color:#a6e22e">interesting</span>: <span style="color:#ae81ff">15</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">fuzzing</span>, <span style="color:#a6e22e">elapsed</span>: <span style="color:#ae81ff">9.0</span><span style="color:#a6e22e">s</span>, <span style="color:#a6e22e">execs</span>: <span style="color:#ae81ff">1019</span> (<span style="color:#ae81ff">113</span><span style="color:#f92672">/</span><span style="color:#a6e22e">sec</span>), <span style="color:#a6e22e">workers</span>: <span style="color:#ae81ff">4</span>, <span style="color:#a6e22e">interesting</span>: <span style="color:#ae81ff">15</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">fuzzing</span>, <span style="color:#a6e22e">elapsed</span>: <span style="color:#ae81ff">12.0</span><span style="color:#a6e22e">s</span>, <span style="color:#a6e22e">execs</span>: <span style="color:#ae81ff">1400</span> (<span style="color:#ae81ff">117</span><span style="color:#f92672">/</span><span style="color:#a6e22e">sec</span>), <span style="color:#a6e22e">workers</span>: <span style="color:#ae81ff">4</span>, <span style="color:#a6e22e">interesting</span>: <span style="color:#ae81ff">15</span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">...</span>
</span></span></code></pre></div><p>需要注意的是：</p>
<ul>
<li>Fuzzing 会消耗大量的内存，在运行时会影响到机器的性能（一运行，小风扇就转了起来）。</li>
<li>Fuzzing 会默认使用 <code>GOMAXPROCS</code>相同的核数，可以通过执行 <code>-parallel</code> 标识来控制数量。</li>
<li>Fuzzing 会默认在运行时，将扩大测试范围的数值写入 <code>$GOCACHE/fuzz</code> 内的模糊缓存目录，目前是没有限制的，可以通过运行 <code>gotip clean -fuzzcache</code> 来清除。</li>
</ul>
<h2 id="总结">总结</h2>
<p>在今天这篇文章中，我们介绍了 Fuzzing 是什么。
简单而言，模糊测试（Fuzzing）在真实环境已经被验证了其有效性，其可以随机生成测试用例去覆盖人为测不到的各种复杂场景，带来很大的收益。</p>
<p>在接下来中，除了依赖开源的 go-fuzz 库外，Go 语言也正式的在支持 Fuzzing，虽然他放了 Go1.17 的鸽子&hellip;</p>
<p>这会对构建 Go 程序健壮性的又一强心剂！</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/ternary-operator/">Go 凭什么不支持三元运算符？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/sync-map/">Go 并发读写 sync.map 的强大之处</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/stop-goroutine/">回答我，停止 Goroutine 有几种方法？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/goroutine-errors/">多 Goroutine 如何优雅处理错误？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/enum/">小技巧分享：在 Go 如何实现枚举？</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/map-slice-concurrency/"
                                                    rel="prev">为什么 Go map 和 slice 是非线程安全的？</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/enum/">小技巧分享：在 Go 如何实现枚举？</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>